home *** CD-ROM | disk | FTP | other *** search
/ MacFormat 1995 July / macformat-026.iso / mac / Shareware City / Developers / berkeleydb1.73 / Berkeley_db / hash / hash.c < prev    next >
Encoding:
C/C++ Source or Header  |  1994-07-27  |  23.8 KB  |  1,015 lines  |  [TEXT/MPS ]

  1. /*-
  2.  * Copyright (c) 1990, 1993
  3.  *    The Regents of the University of California.  All rights reserved.
  4.  *
  5.  * This code is derived from software contributed to Berkeley by
  6.  * Margo Seltzer.
  7.  *
  8.  * Redistribution and use in source and binary forms, with or without
  9.  * modification, are permitted provided that the following conditions
  10.  * are met:
  11.  * 1. Redistributions of source code must retain the above copyright
  12.  *    notice, this list of conditions and the following disclaimer.
  13.  * 2. Redistributions in binary form must reproduce the above copyright
  14.  *    notice, this list of conditions and the following disclaimer in the
  15.  *    documentation and/or other materials provided with the distribution.
  16.  * 3. All advertising materials mentioning features or use of this software
  17.  *    must display the following acknowledgement:
  18.  *    This product includes software developed by the University of
  19.  *    California, Berkeley and its contributors.
  20.  * 4. Neither the name of the University nor the names of its contributors
  21.  *    may be used to endorse or promote products derived from this software
  22.  *    without specific prior written permission.
  23.  *
  24.  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
  25.  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
  26.  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
  27.  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
  28.  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
  29.  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
  30.  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
  31.  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
  32.  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
  33.  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
  34.  * SUCH DAMAGE.
  35.  */
  36.  
  37. #if defined(LIBC_SCCS) && !defined(lint)
  38. static char sccsid[] = "@(#)hash.c    8.4 (Berkeley) 10/12/93";
  39. #endif /* LIBC_SCCS and not lint */
  40.  
  41. #if defined(macintosh) && (defined(powerc) || defined(__powerc))
  42. #include "OurMalloc.h"
  43. #endif
  44.  
  45. #include <sys/param.h>
  46. #include <sys/stat.h>
  47.  
  48. #include <errno.h>
  49. #include <fcntl.h>
  50. #include <stdio.h>
  51. #include <stdlib.h>
  52. #include <string.h>
  53. #include <unistd.h>
  54. #ifdef DEBUG
  55. #include <assert.h>
  56. #endif
  57.  
  58. #ifdef macintosh
  59. #include <sys/fcntl.h>
  60. #include <sys/errno.h>
  61. #endif
  62.  
  63. #include <db.h>
  64. #include "hash.h"
  65. #include "page.h"
  66. #include "extern.h"
  67.  
  68. static int   alloc_segs __P((HTAB *, int));
  69. static int   flush_meta __P((HTAB *));
  70. static int   hash_access __P((HTAB *, ACTION, DBT *, DBT *));
  71. static int   hash_close __P((DB *));
  72. static int   hash_delete __P((const DB *, const DBT *, u_int));
  73. static int   hash_fd __P((const DB *));
  74. static int   hash_get __P((const DB *, const DBT *, DBT *, u_int));
  75. static int   hash_put __P((const DB *, DBT *, const DBT *, u_int));
  76. static void *hash_realloc __P((SEGMENT **, int, int));
  77. static int   hash_seq __P((const DB *, DBT *, DBT *, u_int));
  78. static int   hash_sync __P((const DB *, u_int));
  79. static int   hdestroy __P((HTAB *));
  80. static HTAB *init_hash __P((HTAB *, const char *, HASHINFO *));
  81. static int   init_htab __P((HTAB *, int));
  82. #if BYTE_ORDER == LITTLE_ENDIAN
  83. static void  swap_header __P((HTAB *));
  84. static void  swap_header_copy __P((HASHHDR *, HASHHDR *));
  85. #endif
  86.  
  87. /* Fast arithmetic, relying on powers of 2, */
  88. #define MOD(x, y)        ((x) & ((y) - 1))
  89.  
  90. #define RETURN_ERROR(ERR, LOC)    { save_errno = ERR; goto LOC; }
  91.  
  92. /* Return values */
  93. #define    SUCCESS     (0)
  94. #define    ERROR    (-1)
  95. #define    ABNORMAL (1)
  96.  
  97. #ifdef HASH_STATISTICS
  98. long hash_accesses, hash_collisions, hash_expansions, hash_overflows;
  99. #endif
  100.  
  101. /************************** INTERFACE ROUTINES ***************************/
  102. /* OPEN/CLOSE */
  103.  
  104. extern DB *
  105. __hash_open(file, flags, mode, info, dflags)
  106.     const char *file;
  107.     int flags, mode, dflags;
  108.     const HASHINFO *info;    /* Special directives for create */
  109. {
  110.     HTAB *hashp;
  111.     struct stat statbuf;
  112.     DB *dbp;
  113.     int bpages, hdrsize, new_table, nsegs, save_errno;
  114.  
  115.     if ((flags & O_ACCMODE) == O_WRONLY) {
  116.         errno = EINVAL;
  117.         return (NULL);
  118.     }
  119.  
  120.     if (!(hashp = calloc(1, sizeof(HTAB))))
  121.         return (NULL);
  122.     hashp->fp = -1;
  123.  
  124.     /*
  125.      * Even if user wants write only, we need to be able to read
  126.      * the actual file, so we need to open it read/write. But, the
  127.      * field in the hashp structure needs to be accurate so that
  128.      * we can check accesses.
  129.      */
  130.     hashp->flags = flags;
  131.  
  132.     new_table = 0;
  133.     if (!file || (flags & O_TRUNC) ||
  134.         (stat(file, &statbuf) && (errno == ENOENT))) {
  135.         if (errno == ENOENT)
  136.             errno = 0; /* Just in case someone looks at errno */
  137.         new_table = 1;
  138.     }
  139.     if (file) {
  140. #ifdef macintosh
  141.         if ((hashp->fp = open(file, flags)) == -1)
  142. #else
  143.         if ((hashp->fp = open(file, flags, mode)) == -1)
  144. #endif
  145.             RETURN_ERROR(errno, error0);
  146. #ifndef macintosh
  147.         (void)fcntl(hashp->fp, F_SETFD, 1);
  148. #endif
  149.     }
  150.     if (new_table) {
  151.         if (!(hashp = init_hash(hashp, file, (HASHINFO *)info)))
  152.             RETURN_ERROR(errno, error1);
  153.     } else {
  154.         /* Table already exists */
  155.         if (info && info->hash)
  156.             hashp->hash = info->hash;
  157.         else
  158.             hashp->hash = __default_hash;
  159.  
  160. #ifdef macintosh
  161.         hdrsize = read(hashp->fp, (char *) &hashp->hdr, sizeof(HASHHDR));
  162. #else
  163.         hdrsize = read(hashp->fp, &hashp->hdr, sizeof(HASHHDR));
  164. #endif
  165. #if BYTE_ORDER == LITTLE_ENDIAN
  166.         swap_header(hashp);
  167. #endif
  168.         if (hdrsize == -1)
  169.             RETURN_ERROR(errno, error1);
  170.         if (hdrsize != sizeof(HASHHDR))
  171.             RETURN_ERROR(EFTYPE, error1);
  172.         /* Verify file type, versions and hash function */
  173.         if (hashp->MAGIC != HASHMAGIC)
  174.             RETURN_ERROR(EFTYPE, error1);
  175. #define    OLDHASHVERSION    1
  176.         if (hashp->VERSION != HASHVERSION &&
  177.             hashp->VERSION != OLDHASHVERSION)
  178.             RETURN_ERROR(EFTYPE, error1);
  179.         if (hashp->hash(CHARKEY, sizeof(CHARKEY)) != hashp->H_CHARKEY)
  180.             RETURN_ERROR(EFTYPE, error1);
  181.         /*
  182.          * Figure out how many segments we need.  Max_Bucket is the
  183.          * maximum bucket number, so the number of buckets is
  184.          * max_bucket + 1.
  185.          */
  186.         nsegs = (hashp->MAX_BUCKET + 1 + hashp->SGSIZE - 1) /
  187.              hashp->SGSIZE;
  188.         hashp->nsegs = 0;
  189.         if (alloc_segs(hashp, nsegs))
  190.             /*
  191.              * If alloc_segs fails, table will have been destroyed
  192.              * and errno will have been set.
  193.              */
  194.             return (NULL);
  195.         /* Read in bitmaps */
  196.         bpages = (hashp->SPARES[hashp->OVFL_POINT] +
  197.             (hashp->BSIZE << BYTE_SHIFT) - 1) >>
  198.             (hashp->BSHIFT + BYTE_SHIFT);
  199.  
  200.         hashp->nmaps = bpages;
  201.         (void)memset(&hashp->mapp[0], 0, bpages * sizeof(u_long *));
  202.     }
  203.  
  204.     /* Initialize Buffer Manager */
  205.     if (info && info->cachesize)
  206.         __buf_init(hashp, info->cachesize);
  207.     else
  208.         __buf_init(hashp, DEF_BUFSIZE);
  209.  
  210.     hashp->new_file = new_table;
  211.     hashp->save_file = file && (hashp->flags & O_RDWR);
  212.     hashp->cbucket = -1;
  213.     if (!(dbp = malloc(sizeof(DB)))) {
  214.         save_errno = errno;
  215.         hdestroy(hashp);
  216.         errno = save_errno;
  217.         return (NULL);
  218.     }
  219.     dbp->internal = hashp;
  220.     dbp->close = hash_close;
  221.     dbp->del = hash_delete;
  222.     dbp->fd = hash_fd;
  223.     dbp->get = hash_get;
  224.     dbp->put = hash_put;
  225.     dbp->seq = hash_seq;
  226.     dbp->sync = hash_sync;
  227.     dbp->type = DB_HASH;
  228.  
  229. #ifdef DEBUG
  230.     (void)fprintf(stderr,
  231. "%s\n%s%x\n%s%d\n%s%d\n%s%d\n%s%d\n%s%d\n%s%d\n%s%d\n%s%d\n%s%d\n%s%x\n%s%x\n%s%d\n%s%d\n",
  232.         "init_htab:",
  233.         "TABLE POINTER   ", hashp,
  234.         "BUCKET SIZE     ", hashp->BSIZE,
  235.         "BUCKET SHIFT    ", hashp->BSHIFT,
  236.         "DIRECTORY SIZE  ", hashp->DSIZE,
  237.         "SEGMENT SIZE    ", hashp->SGSIZE,
  238.         "SEGMENT SHIFT   ", hashp->SSHIFT,
  239.         "FILL FACTOR     ", hashp->FFACTOR,
  240.         "MAX BUCKET      ", hashp->MAX_BUCKET,
  241.         "OVFL POINT         ", hashp->OVFL_POINT,
  242.         "LAST FREED      ", hashp->LAST_FREED,
  243.         "HIGH MASK       ", hashp->HIGH_MASK,
  244.         "LOW  MASK       ", hashp->LOW_MASK,
  245.         "NSEGS           ", hashp->nsegs,
  246.         "NKEYS           ", hashp->NKEYS);
  247. #endif
  248. #ifdef HASH_STATISTICS
  249.     hash_overflows = hash_accesses = hash_collisions = hash_expansions = 0;
  250. #endif
  251.     return (dbp);
  252.  
  253. error1:
  254.     if (hashp != NULL)
  255.         (void)close(hashp->fp);
  256.  
  257. error0:
  258.     free(hashp);
  259.     errno = save_errno;
  260.     return (NULL);
  261. }
  262.  
  263. static int
  264. hash_close(dbp)
  265.     DB *dbp;
  266. {
  267.     HTAB *hashp;
  268.     int retval;
  269.  
  270.     if (!dbp)
  271.         return (ERROR);
  272.  
  273.     hashp = (HTAB *)dbp->internal;
  274.     retval = hdestroy(hashp);
  275.     free(dbp);
  276.     return (retval);
  277. }
  278.  
  279. static int
  280. hash_fd(dbp)
  281.     const DB *dbp;
  282. {
  283.     HTAB *hashp;
  284.  
  285.     if (!dbp)
  286.         return (ERROR);
  287.  
  288.     hashp = (HTAB *)dbp->internal;
  289.     if (hashp->fp == -1) {
  290.         errno = ENOENT;
  291.         return (-1);
  292.     }
  293.     return (hashp->fp);
  294. }
  295.  
  296. /************************** LOCAL CREATION ROUTINES **********************/
  297. static HTAB *
  298. init_hash(hashp, file, info)
  299.     HTAB *hashp;
  300.     const char *file;
  301.     HASHINFO *info;
  302. {
  303.     struct stat statbuf;
  304.     int nelem;
  305.  
  306.     nelem = 1;
  307.     hashp->NKEYS = 0;
  308.     hashp->LORDER = BYTE_ORDER;
  309.     hashp->BSIZE = DEF_BUCKET_SIZE;
  310.     hashp->BSHIFT = DEF_BUCKET_SHIFT;
  311.     hashp->SGSIZE = DEF_SEGSIZE;
  312.     hashp->SSHIFT = DEF_SEGSIZE_SHIFT;
  313.     hashp->DSIZE = DEF_DIRSIZE;
  314.     hashp->FFACTOR = DEF_FFACTOR;
  315.     hashp->hash = __default_hash;
  316.     memset(hashp->SPARES, 0, sizeof(hashp->SPARES));
  317.     memset(hashp->BITMAPS, 0, sizeof (hashp->BITMAPS));
  318.  
  319.     /* Fix bucket size to be optimal for file system */
  320.     if (file != NULL) {
  321.         if (stat(file, &statbuf))
  322.             return (NULL);
  323.         hashp->BSIZE = statbuf.st_blksize;
  324.         hashp->BSHIFT = __log2(hashp->BSIZE);
  325.     }
  326.  
  327.     if (info) {
  328.         if (info->bsize) {
  329.             /* Round pagesize up to power of 2 */
  330.             hashp->BSHIFT = __log2(info->bsize);
  331.             hashp->BSIZE = 1 << hashp->BSHIFT;
  332.             if (hashp->BSIZE > MAX_BSIZE) {
  333.                 errno = EINVAL;
  334.                 return (NULL);
  335.             }
  336.         }
  337.         if (info->ffactor)
  338.             hashp->FFACTOR = info->ffactor;
  339.         if (info->hash)
  340.             hashp->hash = info->hash;
  341.         if (info->nelem)
  342.             nelem = info->nelem;
  343.         if (info->lorder) {
  344.             if (info->lorder != BIG_ENDIAN &&
  345.                 info->lorder != LITTLE_ENDIAN) {
  346.                 errno = EINVAL;
  347.                 return (NULL);
  348.             }
  349.             hashp->LORDER = info->lorder;
  350.         }
  351.     }
  352.     /* init_htab should destroy the table and set errno if it fails */
  353.     if (init_htab(hashp, nelem))
  354.         return (NULL);
  355.     else
  356.         return (hashp);
  357. }
  358. /*
  359.  * This calls alloc_segs which may run out of memory.  Alloc_segs will destroy
  360.  * the table and set errno, so we just pass the error information along.
  361.  *
  362.  * Returns 0 on No Error
  363.  */
  364. static int
  365. init_htab(hashp, nelem)
  366.     HTAB *hashp;
  367.     int nelem;
  368. {
  369.     register int nbuckets, nsegs;
  370.     int l2;
  371.  
  372.     /*
  373.      * Divide number of elements by the fill factor and determine a
  374.      * desired number of buckets.  Allocate space for the next greater
  375.      * power of two number of buckets.
  376.      */
  377.     nelem = (nelem - 1) / hashp->FFACTOR + 1;
  378.  
  379.     l2 = __log2(MAX(nelem, 2));
  380.     nbuckets = 1 << l2;
  381.  
  382.     hashp->SPARES[l2] = l2 + 1;
  383.     hashp->SPARES[l2 + 1] = l2 + 1;
  384.     hashp->OVFL_POINT = l2;
  385.     hashp->LAST_FREED = 2;
  386.  
  387.     /* First bitmap page is at: splitpoint l2 page offset 1 */
  388.     if (__init_bitmap(hashp, OADDR_OF(l2, 1), l2 + 1, 0))
  389.         return (-1);
  390.  
  391.     hashp->MAX_BUCKET = hashp->LOW_MASK = nbuckets - 1;
  392.     hashp->HIGH_MASK = (nbuckets << 1) - 1;
  393.     hashp->HDRPAGES = ((MAX(sizeof(HASHHDR), MINHDRSIZE) - 1) >>
  394.         hashp->BSHIFT) + 1;
  395.  
  396.     nsegs = (nbuckets - 1) / hashp->SGSIZE + 1;
  397.     nsegs = 1 << __log2(nsegs);
  398.  
  399.     if (nsegs > hashp->DSIZE)
  400.         hashp->DSIZE = nsegs;
  401.     return (alloc_segs(hashp, nsegs));
  402. }
  403.  
  404. /********************** DESTROY/CLOSE ROUTINES ************************/
  405.  
  406. /*
  407.  * Flushes any changes to the file if necessary and destroys the hashp
  408.  * structure, freeing all allocated space.
  409.  */
  410. static int
  411. hdestroy(hashp)
  412.     HTAB *hashp;
  413. {
  414.     int i, save_errno;
  415.  
  416.     save_errno = 0;
  417.  
  418. #ifdef HASH_STATISTICS
  419.     (void)fprintf(stderr, "hdestroy: accesses %ld collisions %ld\n",
  420.         hash_accesses, hash_collisions);
  421.     (void)fprintf(stderr, "hdestroy: expansions %ld\n",
  422.         hash_expansions);
  423.     (void)fprintf(stderr, "hdestroy: overflows %ld\n",
  424.         hash_overflows);
  425.     (void)fprintf(stderr, "keys %ld maxp %d segmentcount %d\n",
  426.         hashp->NKEYS, hashp->MAX_BUCKET, hashp->nsegs);
  427.  
  428.     for (i = 0; i < NCACHED; i++)
  429.         (void)fprintf(stderr,
  430.             "spares[%d] = %d\n", i, hashp->SPARES[i]);
  431. #endif
  432.     /*
  433.      * Call on buffer manager to free buffers, and if required,
  434.      * write them to disk.
  435.      */
  436.     if (__buf_free(hashp, 1, hashp->save_file))
  437.         save_errno = errno;
  438.     if (hashp->dir) {
  439.         free(*hashp->dir);    /* Free initial segments */
  440.         /* Free extra segments */
  441.         while (hashp->exsegs--)
  442.             free(hashp->dir[--hashp->nsegs]);
  443.         free(hashp->dir);
  444.     }
  445.     if (flush_meta(hashp) && !save_errno)
  446.         save_errno = errno;
  447.     /* Free Bigmaps */
  448.     for (i = 0; i < hashp->nmaps; i++)
  449.         if (hashp->mapp[i])
  450.             free(hashp->mapp[i]);
  451.  
  452.     if (hashp->fp != -1)
  453.         (void)close(hashp->fp);
  454.  
  455.     if (save_errno) {
  456.         errno = save_errno;
  457.         return (ERROR);
  458.     }
  459.     return (SUCCESS);
  460. }
  461. /*
  462.  * Write modified pages to disk
  463.  *
  464.  * Returns:
  465.  *     0 == OK
  466.  *    -1 ERROR
  467.  */
  468. static int
  469. hash_sync(dbp, flags)
  470.     const DB *dbp;
  471.     u_int flags;
  472. {
  473.     HTAB *hashp;
  474.  
  475.     if (flags != 0) {
  476.         errno = EINVAL;
  477.         return (ERROR);
  478.     }
  479.  
  480.     if (!dbp)
  481.         return (ERROR);
  482.  
  483.     hashp = (HTAB *)dbp->internal;
  484.     if (!hashp->save_file)
  485.         return (0);
  486.     if (__buf_free(hashp, 0, 1) || flush_meta(hashp))
  487.         return (ERROR);
  488.     hashp->new_file = 0;
  489.     return (0);
  490. }
  491.  
  492. /*
  493.  * Returns:
  494.  *     0 == OK
  495.  *    -1 indicates that errno should be set
  496.  */
  497. static int
  498. flush_meta(hashp)
  499.     HTAB *hashp;
  500. {
  501.     HASHHDR *whdrp;
  502. #if BYTE_ORDER == LITTLE_ENDIAN
  503.     HASHHDR whdr;
  504. #endif
  505.     int fp, i, wsize;
  506.  
  507.     if (!hashp->save_file)
  508.         return (0);
  509.     hashp->MAGIC = HASHMAGIC;
  510.     hashp->VERSION = HASHVERSION;
  511.     hashp->H_CHARKEY = hashp->hash(CHARKEY, sizeof(CHARKEY));
  512.  
  513.     fp = hashp->fp;
  514.     whdrp = &hashp->hdr;
  515. #if BYTE_ORDER == LITTLE_ENDIAN
  516.     whdrp = &whdr;
  517.     swap_header_copy(&hashp->hdr, whdrp);
  518. #endif
  519.     if ((lseek(fp, (off_t)0, SEEK_SET) == -1) ||
  520. #ifdef macintosh
  521.         ((wsize = write(fp, (char *) whdrp, sizeof(HASHHDR))) == -1))
  522. #else
  523.         ((wsize = write(fp, whdrp, sizeof(HASHHDR))) == -1))
  524. #endif
  525.         return (-1);
  526.     else
  527.         if (wsize != sizeof(HASHHDR)) {
  528.             errno = EFTYPE;
  529.             hashp->errno = errno;
  530.             return (-1);
  531.         }
  532.     for (i = 0; i < NCACHED; i++)
  533.         if (hashp->mapp[i])
  534.             if (__put_page(hashp, (char *)hashp->mapp[i],
  535.                 hashp->BITMAPS[i], 0, 1))
  536.                 return (-1);
  537.     return (0);
  538. }
  539.  
  540. /*******************************SEARCH ROUTINES *****************************/
  541. /*
  542.  * All the access routines return
  543.  *
  544.  * Returns:
  545.  *     0 on SUCCESS
  546.  *     1 to indicate an external ERROR (i.e. key not found, etc)
  547.  *    -1 to indicate an internal ERROR (i.e. out of memory, etc)
  548.  */
  549. static int
  550. hash_get(dbp, key, data, flag)
  551.     const DB *dbp;
  552.     const DBT *key;
  553.     DBT *data;
  554.     u_int flag;
  555. {
  556.     HTAB *hashp;
  557.  
  558.     hashp = (HTAB *)dbp->internal;
  559.     if (flag) {
  560.         hashp->errno = errno = EINVAL;
  561.         return (ERROR);
  562.     }
  563.     return (hash_access(hashp, HASH_GET, (DBT *)key, data));
  564. }
  565.  
  566. static int
  567. hash_put(dbp, key, data, flag)
  568.     const DB *dbp;
  569.     DBT *key;
  570.     const DBT *data;
  571.     u_int flag;
  572. {
  573.     HTAB *hashp;
  574.  
  575.     hashp = (HTAB *)dbp->internal;
  576.     if (flag && flag != R_NOOVERWRITE) {
  577.         hashp->errno = errno = EINVAL;
  578.         return (ERROR);
  579.     }
  580.     if ((hashp->flags & O_ACCMODE) == O_RDONLY) {
  581.         hashp->errno = errno = EPERM;
  582.         return (ERROR);
  583.     }
  584.     return (hash_access(hashp, flag == R_NOOVERWRITE ?
  585.         HASH_PUTNEW : HASH_PUT, (DBT *)key, (DBT *)data));
  586. }
  587.  
  588. static int
  589. hash_delete(dbp, key, flag)
  590.     const DB *dbp;
  591.     const DBT *key;
  592.     u_int flag;        /* Ignored */
  593. {
  594.     HTAB *hashp;
  595.  
  596.     hashp = (HTAB *)dbp->internal;
  597.     if (flag && flag != R_CURSOR) {
  598.         hashp->errno = errno = EINVAL;
  599.         return (ERROR);
  600.     }
  601.     if ((hashp->flags & O_ACCMODE) == O_RDONLY) {
  602.         hashp->errno = errno = EPERM;
  603.         return (ERROR);
  604.     }
  605.     return (hash_access(hashp, HASH_DELETE, (DBT *)key, NULL));
  606. }
  607.  
  608. /*
  609.  * Assume that hashp has been set in wrapper routine.
  610.  */
  611. static int
  612. hash_access(hashp, action, key, val)
  613.     HTAB *hashp;
  614.     ACTION action;
  615.     DBT *key, *val;
  616. {
  617.     register BUFHEAD *rbufp;
  618.     BUFHEAD *bufp, *save_bufp;
  619.     register u_short *bp;
  620.     register int n, ndx, off, size;
  621.     register char *kp;
  622.     u_short pageno;
  623.  
  624. #ifdef HASH_STATISTICS
  625.     hash_accesses++;
  626. #endif
  627.  
  628.     off = hashp->BSIZE;
  629.     size = key->size;
  630.     kp = (char *)key->data;
  631.     rbufp = __get_buf(hashp, __call_hash(hashp, kp, size), NULL, 0);
  632.     if (!rbufp)
  633.         return (ERROR);
  634.     save_bufp = rbufp;
  635.  
  636.     /* Pin the bucket chain */
  637.     rbufp->flags |= BUF_PIN;
  638.     for (bp = (u_short *)rbufp->page, n = *bp++, ndx = 1; ndx < n;)
  639.         if (bp[1] >= REAL_KEY) {
  640.             /* Real key/data pair */
  641.             if (size == off - *bp &&
  642.                 memcmp(kp, rbufp->page + *bp, size) == 0)
  643.                 goto found;
  644.             off = bp[1];
  645. #ifdef HASH_STATISTICS
  646.             hash_collisions++;
  647. #endif
  648.             bp += 2;
  649.             ndx += 2;
  650.         } else if (bp[1] == OVFLPAGE) {
  651.             rbufp = __get_buf(hashp, *bp, rbufp, 0);
  652.             if (!rbufp) {
  653.                 save_bufp->flags &= ~BUF_PIN;
  654.                 return (ERROR);
  655.             }
  656.             /* FOR LOOP INIT */
  657.             bp = (u_short *)rbufp->page;
  658.             n = *bp++;
  659.             ndx = 1;
  660.             off = hashp->BSIZE;
  661.         } else if (bp[1] < REAL_KEY) {
  662.             if ((ndx =
  663.                 __find_bigpair(hashp, rbufp, ndx, kp, size)) > 0)
  664.                 goto found;
  665.             if (ndx == -2) {
  666.                 bufp = rbufp;
  667.                 if (!(pageno =
  668.                     __find_last_page(hashp, &bufp))) {
  669.                     ndx = 0;
  670.                     rbufp = bufp;
  671.                     break;    /* FOR */
  672.                 }
  673.                 rbufp = __get_buf(hashp, pageno, bufp, 0);
  674.                 if (!rbufp) {
  675.                     save_bufp->flags &= ~BUF_PIN;
  676.                     return (ERROR);
  677.                 }
  678.                 /* FOR LOOP INIT */
  679.                 bp = (u_short *)rbufp->page;
  680.                 n = *bp++;
  681.                 ndx = 1;
  682.                 off = hashp->BSIZE;
  683.             } else {
  684.                 save_bufp->flags &= ~BUF_PIN;
  685.                 return (ERROR);
  686.             }
  687.         }
  688.  
  689.     /* Not found */
  690.     switch (action) {
  691.     case HASH_PUT:
  692.     case HASH_PUTNEW:
  693.         if (__addel(hashp, rbufp, key, val)) {
  694.             save_bufp->flags &= ~BUF_PIN;
  695.             return (ERROR);
  696.         } else {
  697.             save_bufp->flags &= ~BUF_PIN;
  698.             return (SUCCESS);
  699.         }
  700.     case HASH_GET:
  701.     case HASH_DELETE:
  702.     default:
  703.         save_bufp->flags &= ~BUF_PIN;
  704.         return (ABNORMAL);
  705.     }
  706.  
  707. found:
  708.     switch (action) {
  709.     case HASH_PUTNEW:
  710.         save_bufp->flags &= ~BUF_PIN;
  711.         return (ABNORMAL);
  712.     case HASH_GET:
  713.         bp = (u_short *)rbufp->page;
  714.         if (bp[ndx + 1] < REAL_KEY) {
  715.             if (__big_return(hashp, rbufp, ndx, val, 0))
  716.                 return (ERROR);
  717.         } else {
  718.             val->data = (u_char *)rbufp->page + (int)bp[ndx + 1];
  719.             val->size = bp[ndx] - bp[ndx + 1];
  720.         }
  721.         break;
  722.     case HASH_PUT:
  723.         if ((__delpair(hashp, rbufp, ndx)) ||
  724.             (__addel(hashp, rbufp, key, val))) {
  725.             save_bufp->flags &= ~BUF_PIN;
  726.             return (ERROR);
  727.         }
  728.         break;
  729.     case HASH_DELETE:
  730.         if (__delpair(hashp, rbufp, ndx))
  731.             return (ERROR);
  732.         break;
  733.     default:
  734.         abort();
  735.     }
  736.     save_bufp->flags &= ~BUF_PIN;
  737.     return (SUCCESS);
  738. }
  739.  
  740. static int
  741. hash_seq(dbp, key, data, flag)
  742.     const DB *dbp;
  743.     DBT *key, *data;
  744.     u_int flag;
  745. {
  746.     register u_int bucket;
  747.     register BUFHEAD *bufp;
  748.     HTAB *hashp;
  749.     u_short *bp, ndx;
  750.  
  751.     hashp = (HTAB *)dbp->internal;
  752.     if (flag && flag != R_FIRST && flag != R_NEXT) {
  753.         hashp->errno = errno = EINVAL;
  754.         return (ERROR);
  755.     }
  756. #ifdef HASH_STATISTICS
  757.     hash_accesses++;
  758. #endif
  759.     if ((hashp->cbucket < 0) || (flag == R_FIRST)) {
  760.         hashp->cbucket = 0;
  761.         hashp->cndx = 1;
  762.         hashp->cpage = NULL;
  763.     }
  764.  
  765.     for (bp = NULL; !bp || !bp[0]; ) {
  766.         if (!(bufp = hashp->cpage)) {
  767.             for (bucket = hashp->cbucket;
  768.                 bucket <= hashp->MAX_BUCKET;
  769.                 bucket++, hashp->cndx = 1) {
  770.                 bufp = __get_buf(hashp, bucket, NULL, 0);
  771.                 if (!bufp)
  772.                     return (ERROR);
  773.                 hashp->cpage = bufp;
  774.                 bp = (u_short *)bufp->page;
  775.                 if (bp[0])
  776.                     break;
  777.             }
  778.             hashp->cbucket = bucket;
  779.             if (hashp->cbucket > hashp->MAX_BUCKET) {
  780.                 hashp->cbucket = -1;
  781.                 return (ABNORMAL);
  782.             }
  783.         } else
  784.             bp = (u_short *)hashp->cpage->page;
  785.  
  786. #ifdef DEBUG
  787.         assert(bp);
  788.         assert(bufp);
  789. #endif
  790.         while (bp[hashp->cndx + 1] == OVFLPAGE) {
  791.             bufp = hashp->cpage =
  792.                 __get_buf(hashp, bp[hashp->cndx], bufp, 0);
  793.             if (!bufp)
  794.                 return (ERROR);
  795.             bp = (u_short *)(bufp->page);
  796.             hashp->cndx = 1;
  797.         }
  798.         if (!bp[0]) {
  799.             hashp->cpage = NULL;
  800.             ++hashp->cbucket;
  801.         }
  802.     }
  803.     ndx = hashp->cndx;
  804.     if (bp[ndx + 1] < REAL_KEY) {
  805.         if (__big_keydata(hashp, bufp, key, data, 1))
  806.             return (ERROR);
  807.     } else {
  808.         key->data = (u_char *)hashp->cpage->page + bp[ndx];
  809.         key->size = (ndx > 1 ? bp[ndx - 1] : hashp->BSIZE) - bp[ndx];
  810.         data->data = (u_char *)hashp->cpage->page + bp[ndx + 1];
  811.         data->size = bp[ndx] - bp[ndx + 1];
  812.         ndx += 2;
  813.         if (ndx > bp[0]) {
  814.             hashp->cpage = NULL;
  815.             hashp->cbucket++;
  816.             hashp->cndx = 1;
  817.         } else
  818.             hashp->cndx = ndx;
  819.     }
  820.     return (SUCCESS);
  821. }
  822.  
  823. /********************************* UTILITIES ************************/
  824.  
  825. /*
  826.  * Returns:
  827.  *     0 ==> OK
  828.  *    -1 ==> Error
  829.  */
  830. extern int
  831. __expand_table(hashp)
  832.     HTAB *hashp;
  833. {
  834.     u_int old_bucket, new_bucket;
  835.     int dirsize, new_segnum, spare_ndx;
  836.  
  837. #ifdef HASH_STATISTICS
  838.     hash_expansions++;
  839. #endif
  840.     new_bucket = ++hashp->MAX_BUCKET;
  841.     old_bucket = (hashp->MAX_BUCKET & hashp->LOW_MASK);
  842.  
  843.     new_segnum = new_bucket >> hashp->SSHIFT;
  844.  
  845.     /* Check if we need a new segment */
  846.     if (new_segnum >= hashp->nsegs) {
  847.         /* Check if we need to expand directory */
  848.         if (new_segnum >= hashp->DSIZE) {
  849.             /* Reallocate directory */
  850.             dirsize = hashp->DSIZE * sizeof(SEGMENT *);
  851.             if (!hash_realloc(&hashp->dir, dirsize, dirsize << 1))
  852.                 return (-1);
  853.             hashp->DSIZE = dirsize << 1;
  854.         }
  855.         if (!(hashp->dir[new_segnum] =
  856.             calloc(hashp->SGSIZE, sizeof(SEGMENT))))
  857.             return (-1);
  858.         hashp->exsegs++;
  859.         hashp->nsegs++;
  860.     }
  861.     /*
  862.      * If the split point is increasing (MAX_BUCKET's log base 2
  863.      * * increases), we need to copy the current contents of the spare
  864.      * split bucket to the next bucket.
  865.      */
  866.     spare_ndx = __log2(hashp->MAX_BUCKET + 1);
  867.     if (spare_ndx > hashp->OVFL_POINT) {
  868.         hashp->SPARES[spare_ndx] = hashp->SPARES[hashp->OVFL_POINT];
  869.         hashp->OVFL_POINT = spare_ndx;
  870.     }
  871.  
  872.     if (new_bucket > hashp->HIGH_MASK) {
  873.         /* Starting a new doubling */
  874.         hashp->LOW_MASK = hashp->HIGH_MASK;
  875.         hashp->HIGH_MASK = new_bucket | hashp->LOW_MASK;
  876.     }
  877.     /* Relocate records to the new bucket */
  878.     return (__split_page(hashp, old_bucket, new_bucket));
  879. }
  880.  
  881. /*
  882.  * If realloc guarantees that the pointer is not destroyed if the realloc
  883.  * fails, then this routine can go away.
  884.  */
  885. static void *
  886. hash_realloc(p_ptr, oldsize, newsize)
  887.     SEGMENT **p_ptr;
  888.     int oldsize, newsize;
  889. {
  890.     register void *p;
  891.  
  892.     if (p = malloc(newsize)) {
  893.         memmove(p, *p_ptr, oldsize);
  894.         memset((char *)p + oldsize, 0, newsize - oldsize);
  895.         free(*p_ptr);
  896.         *p_ptr = p;
  897.     }
  898.     return (p);
  899. }
  900.  
  901. extern u_int
  902. __call_hash(hashp, k, len)
  903.     HTAB *hashp;
  904.     char *k;
  905.     int len;
  906. {
  907.     int n, bucket;
  908.  
  909.     n = hashp->hash(k, len);
  910.     bucket = n & hashp->HIGH_MASK;
  911.     if (bucket > hashp->MAX_BUCKET)
  912.         bucket = bucket & hashp->LOW_MASK;
  913.     return (bucket);
  914. }
  915.  
  916. /*
  917.  * Allocate segment table.  On error, destroy the table and set errno.
  918.  *
  919.  * Returns 0 on success
  920.  */
  921. static int
  922. alloc_segs(hashp, nsegs)
  923.     HTAB *hashp;
  924.     int nsegs;
  925. {
  926.     register int i;
  927.     register SEGMENT store;
  928.  
  929.     int save_errno;
  930.  
  931.     if (!(hashp->dir = calloc(hashp->DSIZE, sizeof(SEGMENT *)))) {
  932.         save_errno = errno;
  933.         (void)hdestroy(hashp);
  934.         errno = save_errno;
  935.         return (-1);
  936.     }
  937.     /* Allocate segments */
  938.     store = calloc(nsegs << hashp->SSHIFT, sizeof(SEGMENT));
  939.     if (!store) {
  940.         save_errno = errno;
  941.         (void)hdestroy(hashp);
  942.         errno = save_errno;
  943.         return (-1);
  944.     }
  945.     for (i = 0; i < nsegs; i++, hashp->nsegs++)
  946.         hashp->dir[i] = &store[i << hashp->SSHIFT];
  947.     return (0);
  948. }
  949.  
  950. #if BYTE_ORDER == LITTLE_ENDIAN
  951. /*
  952.  * Hashp->hdr needs to be byteswapped.
  953.  */
  954. static void
  955. swap_header_copy(srcp, destp)
  956.     HASHHDR *srcp, *destp;
  957. {
  958.     int i;
  959.  
  960.     BLSWAP_COPY(srcp->magic, destp->magic);
  961.     BLSWAP_COPY(srcp->version, destp->version);
  962.     BLSWAP_COPY(srcp->lorder, destp->lorder);
  963.     BLSWAP_COPY(srcp->bsize, destp->bsize);
  964.     BLSWAP_COPY(srcp->bshift, destp->bshift);
  965.     BLSWAP_COPY(srcp->dsize, destp->dsize);
  966.     BLSWAP_COPY(srcp->ssize, destp->ssize);
  967.     BLSWAP_COPY(srcp->sshift, destp->sshift);
  968.     BLSWAP_COPY(srcp->ovfl_point, destp->ovfl_point);
  969.     BLSWAP_COPY(srcp->last_freed, destp->last_freed);
  970.     BLSWAP_COPY(srcp->max_bucket, destp->max_bucket);
  971.     BLSWAP_COPY(srcp->high_mask, destp->high_mask);
  972.     BLSWAP_COPY(srcp->low_mask, destp->low_mask);
  973.     BLSWAP_COPY(srcp->ffactor, destp->ffactor);
  974.     BLSWAP_COPY(srcp->nkeys, destp->nkeys);
  975.     BLSWAP_COPY(srcp->hdrpages, destp->hdrpages);
  976.     BLSWAP_COPY(srcp->h_charkey, destp->h_charkey);
  977.     for (i = 0; i < NCACHED; i++) {
  978.         BLSWAP_COPY(srcp->spares[i], destp->spares[i]);
  979.         BSSWAP_COPY(srcp->bitmaps[i], destp->bitmaps[i]);
  980.     }
  981. }
  982.  
  983. static void
  984. swap_header(hashp)
  985.     HTAB *hashp;
  986. {
  987.     HASHHDR *hdrp;
  988.     int i;
  989.  
  990.     hdrp = &hashp->hdr;
  991.  
  992.     BLSWAP(hdrp->magic);
  993.     BLSWAP(hdrp->version);
  994.     BLSWAP(hdrp->lorder);
  995.     BLSWAP(hdrp->bsize);
  996.     BLSWAP(hdrp->bshift);
  997.     BLSWAP(hdrp->dsize);
  998.     BLSWAP(hdrp->ssize);
  999.     BLSWAP(hdrp->sshift);
  1000.     BLSWAP(hdrp->ovfl_point);
  1001.     BLSWAP(hdrp->last_freed);
  1002.     BLSWAP(hdrp->max_bucket);
  1003.     BLSWAP(hdrp->high_mask);
  1004.     BLSWAP(hdrp->low_mask);
  1005.     BLSWAP(hdrp->ffactor);
  1006.     BLSWAP(hdrp->nkeys);
  1007.     BLSWAP(hdrp->hdrpages);
  1008.     BLSWAP(hdrp->h_charkey);
  1009.     for (i = 0; i < NCACHED; i++) {
  1010.         BLSWAP(hdrp->spares[i]);
  1011.         BSSWAP(hdrp->bitmaps[i]);
  1012.     }
  1013. }
  1014. #endif
  1015.